package com.cool.feiyan.ui.home

import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.cool.feiyan.*

class HomeFragment : Fragment() {

    //private lateinit var homeViewModel: HomeViewModel
    private lateinit var home_root : View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel::class.java)
        home_root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = home_root.findViewById(R.id.text_home)
        homeViewModel.text.observe(this, Observer {
            textView.text = it
        })

        configureFlushButton()
        configureDateSpinner()
        configure车次Spinner()
        configureQueryButton()

        异步取数()

        return home_root
    }

    private fun configureFlushButton() {
        val queryButton : Button = home_root.findViewById(R.id.button_id_刷新)
        queryButton.setOnClickListener { view : View ->
            异步取数()
        }
    }

    private fun configureQueryButton() {
        val queryButton : Button = home_root.findViewById(R.id.button_id_查询)
        queryButton.setOnClickListener { view : View ->
            var date : String = home_root.findViewById<Spinner>(R.id.spinner_date).selectedItem.toString()
            var 车次 : String = home_root.findViewById<Spinner>(R.id.spinner_车次).selectedItem.toString()
            var 地区 : String = home_root.findViewById<EditText>(R.id.edit_text_地区).text.toString()
            if (date.compareTo("全部") == 0)
                date = ""
            if(车次.compareTo("全部") == 0)
                车次 = ""
            查询(date, 车次, 地区)
        }
    }

    private fun configureDateSpinner() {
        class OnDateItemSelected : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
                // An item was selected. You can retrieve the selected item using
                val item : String = parent.getItemAtPosition(pos) as String
                var dateList : MutableList<FeiYanData> = (activity as MainActivity).totalResultList
                if (item.compareTo("全部") != 0) { // 选中了一个日期
                    for (index in 0 until (activity as MainActivity).日期分类.size) {
                        if(item.compareTo((activity as MainActivity).日期分类[index].依据) == 0) // 找到了指定日期
                            dateList = (activity as MainActivity).日期分类[index].feiYanData
                    }
                }
                Log.d("DateSpinner", dateList.size.toString())
                按车次分类(dateList)
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                // Another interface callback
            }
        }
        val dateSpinner : Spinner = home_root.findViewById(R.id.spinner_date)
        dateSpinner.onItemSelectedListener = OnDateItemSelected()
    }

    private fun configure车次Spinner() {
        val carSpinner : Spinner = home_root.findViewById(R.id.spinner_车次)
    }

    private fun 异步取数() {
        val downloadJsonData : DownloadJsonData = DownloadJsonData(home_root, this, activity as MainActivity)
        downloadJsonData.execute()
    }

    private fun 按日期分类(result: MutableList<FeiYanData>) {
        // 找出来不同的日期
        (activity as MainActivity).日期分类.clear()
        (activity as MainActivity).日期分类.add(分类数据())
        (activity as MainActivity).日期分类[0].依据 = "全部"
        (activity as MainActivity).日期分类[0].feiYanData = result

        for (index in 0 until result.size) {
            var position : Int = 0
            while ( position < (activity as MainActivity).日期分类.size) {
                if ((activity as MainActivity).日期分类[position].依据.compareTo(result[index].日期) == 0)
                    break
                ++position
            }

            if(position < (activity as MainActivity).日期分类.size) { // 找到了
                (activity as MainActivity).日期分类[position].feiYanData.add(result[index])
            }
            else {// 没找到
                (activity as MainActivity).日期分类.add(分类数据())
                (activity as MainActivity).日期分类[position].依据 = result[index].日期
                (activity as MainActivity).日期分类[position].feiYanData.add(result[index])
            }
        }
        // 设置 spinner
        BindToSpinner(R.id.spinner_date, (activity as MainActivity).日期分类)
    }

    private fun 按车次分类(result: MutableList<FeiYanData>) {
        (activity as MainActivity).车次分类.clear()
        (activity as MainActivity).车次分类.add(分类数据())
        (activity as MainActivity).车次分类[0].依据 = "全部"
        (activity as MainActivity).车次分类[0].feiYanData = result

        for (index in 0 until result.size) {
            var position : Int = 0
            while ( position < (activity as MainActivity).车次分类.size) {
                if ((activity as MainActivity).车次分类[position].依据.compareTo(result[index].车次_车牌_航班号_场所名, true) == 0)
                    break
                ++position
            }

            if(position < (activity as MainActivity).车次分类.size) { // 找到了
                (activity as MainActivity).车次分类[position].feiYanData.add(result[index])
            }
            else {// 没找到
                (activity as MainActivity).车次分类.add(分类数据())
                (activity as MainActivity).车次分类[position].依据 = result[index].车次_车牌_航班号_场所名
                (activity as MainActivity).车次分类[position].feiYanData.add(result[index])
            }
        }
        // 设置 spinner
        BindToSpinner(R.id.spinner_车次, (activity as MainActivity).车次分类)
    }

    private fun 按地区分类(result: MutableList<FeiYanData>) {

    }

    fun 查询(dateString : String, 车次 : String, 地区 : String) {

        var dataList : MutableList<FeiYanData> = (activity as MainActivity).totalResultList
        var resultList1 : MutableList<FeiYanData> = mutableListOf()

        // https://www.tutorialkart.com/kotlin/compare-strings-in-kotlin-example/
        // https://beginnersbook.com/2019/03/kotlin-data-class/
        // https://www.bennyhuo.com/2018/12/02/deepcopy/

        if(!dateString.isEmpty())
            for (item in dataList) {
                if(item.日期.compareTo(dateString) == 0)
                    resultList1.add(item)
            }
        else
            resultList1 = dataList // 没有输入日期，则找到全部的数据

        var resultList2 : MutableList<FeiYanData> = mutableListOf()
        if (!车次.isEmpty())
            for (item in resultList1) {
                if(item.车次_车牌_航班号_场所名.compareTo(车次, false) == 0)
                    resultList2.add(item)
            }
        else
            resultList2 = resultList1

        var resultList3 : MutableList<FeiYanData> = mutableListOf()
        if (!地区.isEmpty())
            for (item in resultList2) {
                if(item.车次_车牌_航班号_场所名.contains(地区, false)
                    || item.线索来源名称.contains(地区, false)
                    || item.出发站.contains(地区, false)
                    || item.到达站.contains(地区, false)
                    || item.车次附加描述.contains(地区, false))
                    resultList3.add(item)
            }
        else
            resultList3 = resultList2

        // 仔细考滤 MVC 的用法 2020-02-02
        (activity as MainActivity).resultList = resultList3

        val query_count = home_root.findViewById<TextView>(R.id.text_view_query_count)
        query_count.text = "查询到 " + resultList3.size.toString() + " 条数据。"
    }

    private fun BindToSpinner(resource_id : Int, data : MutableList<分类数据>) {
        var spinner : Spinner = home_root.findViewById(resource_id)
        val listKeySort : MutableList<String> = mutableListOf()
        for (index in 1 until data.size) {
            listKeySort.add(data[index].依据)
        }

        listKeySort.sort()
        val listKey : MutableList<String> = mutableListOf()
        listKey.add(data[0].依据) // 第一项不参与排序
        listKey.addAll(listKeySort)

        val arrayAdapter = ArrayAdapter(activity as Context, android.R.layout.simple_spinner_item, listKey)
        spinner.adapter = arrayAdapter
    }

    private class DownloadJsonData(homeView: View, homeFragment: HomeFragment, activity: MainActivity) : AsyncTask<Void, Void, MutableList<FeiYanData>>() {

        private val _homeView : View
        private val _homeFragment : HomeFragment
        private val _activity : MainActivity

        private val _button_flush : Button
        private val _button_query : Button
        private val _update_count : TextView
        private val _edit_text_地区 : EditText

        init {
            _homeView = homeView
            _homeFragment = homeFragment
            _activity = activity

            _button_flush = _homeView.findViewById(R.id.button_id_刷新)
            _button_query = _homeView.findViewById(R.id.button_id_查询)
            _update_count = _homeView.findViewById(R.id.text_view_update_count)
            _edit_text_地区 = _homeView.findViewById(R.id.edit_text_地区)
        }

        override fun onPreExecute() {
            super.onPreExecute()
            _button_flush.setEnabled(false)
            _button_query.setEnabled(false)
            _edit_text_地区.setEnabled(false)
        }

        override fun doInBackground(vararg params: Void?): MutableList<FeiYanData> {
            var queryData : QueryData = QueryData()
            queryData.QueryAsync()
            var feiYanDataList : MutableList<FeiYanData> = queryData.ParseJson()
            return feiYanDataList
        }

        override fun onPostExecute(result: MutableList<FeiYanData>) {
            super.onPostExecute(result)
            _activity.totalResultList = result
            _homeFragment.按日期分类(result)
            //_homeFragment.按车次分类(result)
            //_homeFragment.按地区分类(result)

            _button_flush.setEnabled(true)
            _button_query.setEnabled(true)
            _edit_text_地区.setEnabled(true)
            _update_count.text = "更新到" + result.size.toString() + " 条数据。"
        }
    }
}
